package org.ofbiz.wvtools.email;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilValidate;

public class EmailUtils {

//	// 这个是你的邮箱用户名
    public String username = "";
    // 你的邮箱密码
    public String password = "";

    private static String module = EmailUtils.class.getName();

    public EmailUtils() {
    }

    /**
     * 用来进行服务器对用户的认证
     */
    public class Email_Autherticator extends Authenticator {
	public Email_Autherticator() {
	    super();
	}

	public Email_Autherticator(String user, String pwd) {
	    super();
	    username = user;
	    password = pwd;
	}

	public PasswordAuthentication getPasswordAuthentication() {
	    return new PasswordAuthentication(username, password);
	}
    }

    /**
     * 此段代码用来发送普通电子邮件
     * 
     * @throws UnsupportedEncodingException
     * @throws Exception
     */
    public String send(String host, String username, String password, String mail_head_name, String mail_head_value,
	    String mail_to, String mail_from, String mail_subject, String mail_body, String personalName) {
	String isSend = "failure";
	// 获取邮件服务器配置
	try {
	    // 发送者邮箱
	    mail_from = username;
	    Properties props = new Properties(); // 获取系统环境
	    Authenticator auth = new Email_Autherticator(username, password); // 进行邮件服务器用户认证
	    props.put("mail.smtp.host", host);
	    props.put("mail.smtp.auth", "true");
	    props.put("mail.smtp.port", "587");
	    Session session = Session.getDefaultInstance(props, auth);
	    // 设置session,和邮件服务器进行通讯。
	    MimeMessage message = new MimeMessage(session);
	    // message.setContent("foobar, "application/x-foobar"); // 设置邮件格式
	    message.setSubject(mail_subject); // 设置邮件主题
	    message.setText(mail_body); // 设置邮件正文
	    message.setHeader(mail_head_name, mail_head_value); // 设置邮件标题
	    message.setSentDate(new Date()); // 设置邮件发送日期
	    Address address = new InternetAddress(mail_from, personalName);
	    message.setFrom(address); // 设置邮件发送者的地址
	    Address toAddress = new InternetAddress(mail_to); // 设置邮件接收方的地址
	    message.addRecipient(Message.RecipientType.TO, toAddress);
	    isSend = "sending";
	    Transport.send(message); // 发送邮件
	    isSend = "success";
	    System.out.println("send ok!");
	} catch (MessagingException e) {
	    isSend = "failure";
	    Debug.logError(e.getMessage(), module);
	} catch (UnsupportedEncodingException e) {
	    isSend = "failure";
	    Debug.logError(e.getMessage(), module);
	}
	return isSend;
    }

    public String sendHtml(String host, String username, String password, String mail_head_name, String mail_head_value,
	    String mail_to, String mail_from, String mail_subject, String mail_body, String personalName,
	    String filePath) {

	String isSend = "failure";

	// 给消息对象设置发件人/收件人/主题/发信时间
	try {

	    mail_from = username;
	    Properties props = new Properties();
	    props.put("mail.smtp.host", host);
	    props.put("mail.smtp.auth", "true");
	    String popPort = "587";
	    props.put("mail.smtp.port", "587");
	    // 开启SSL
	    props.put("mail.smtp.starttls.enable", "true");
	    props.put("mail.smtp.socketFactory.port", popPort);
	    props.put("mail.smtp.socketFactory.fallback", "false");
	    Session s = Session.getInstance(props);
	    s.setDebug(true);
	    MimeMessage message = new MimeMessage(s);

	    String nick = javax.mail.internet.MimeUtility.encodeText(personalName);
	    message.setFrom(new InternetAddress(nick + "<" + mail_from + ">"));// 设置邮件发送者的地址

	    InternetAddress to = new InternetAddress(mail_to);
	    message.setRecipient(Message.RecipientType.TO, to);
	    message.setSubject(mail_subject);
	    message.setSentDate(new Date());

	    MimeBodyPart attch = new MimeBodyPart();
	    if (UtilValidate.isNotEmpty(filePath)) {
		// 设置附件
		DataHandler dh = new DataHandler(new FileDataSource(filePath));
//		String name = dh.getName();
		attch.setDataHandler(dh);
		attch.setFileName(MimeUtility.encodeText("OfferLetter.pdf")); // 设置中文编码
	    }

	    // 给消息对象设置内容
	    BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
	    mdp.setContent(mail_body, "text/html;charset=gb2312");// 给BodyPart对象设置内容和格式/编码方式
	    Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对
	    // 象(事实上可以存放多个)
	    mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
	    if (UtilValidate.isNotEmpty(filePath)) {
		mm.addBodyPart(attch); // 加入附件
	    }

	    message.setContent(mm);// 把mm作为消息对象的内容

	    message.saveChanges();
	    Transport transport = s.getTransport("smtp");

	    isSend = "sending";
	    transport.connect(host, username, password);
	    transport.sendMessage(message, message.getAllRecipients());
	    transport.close();
	    isSend = "success";
	    // System.out.println("发送成功!");

	    Debug.log(mail_to, module);
	    // System.out.println("send ok!");
	} catch (MessagingException e) {
	    isSend = "failure";
	    Debug.logError(e.getMessage(), module);
	} catch (UnsupportedEncodingException e) {
	    isSend = "failure";
	    Debug.logError(e.getMessage(), module);
	}
	return isSend;

    }

    public static void main(String[] args) {

	EmailUtils sendmail = new EmailUtils();
	// 邮箱服务器
	String host = "smtp.partner.outlook.cn";
	// 这个是使用到的邮箱
	String username = "eim@kejicloud.cn";
	// 邮箱密码
	String password = "eim.2020";

	String mail_head_name = "测试";

	String mail_head_value = "测试";
	// 邮件接收者
	String mail_to = "33333@126.com";
	// 邮件发送者
	String mail_from = "eim@kejicloud.cn";
	// 邮件标题
	String mail_subject = "测试subject";
	// 邮件内容
	// String mail_body = "this is the mail_body of this test mail";
	String mail_body = "<table border='1' bgColor='red'><tr><td>发送一个表格</td></tr></table>";// HTML代码

	// 发件人昵称
	String personalName = "EIM";
	try {
	    sendmail.sendHtml(host, username, password, mail_head_name, mail_head_value, mail_to, mail_from,
		    mail_subject, mail_body, personalName, "");
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }

}
